/*
 * This program is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation, either version 3 of the License, or (at your option) any later
 * version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program. If not, see <http://www.gnu.org/licenses/>.
 */
package org.merak.core.web;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.merak.core.Application;
import org.merak.core.model.parameter.ParameterException;

public class HttpRequest extends HttpServletRequestWrapper {

	//~ Attributes ///////////////////////////////////////////////////////////////
	//****************************************************************************
	private Map<String,WebParameter> params           = new HashMap<String,WebParameter>();
	private boolean                  hasUploadRequest = false;
	private int                      uploadCount      = 0;

	//~ Constructors /////////////////////////////////////////////////////////////
	//****************************************************************************
	public HttpRequest(HttpServletRequest request) throws FileUploadException {

		/* Wrap the HttpServletRequest:
		/* Methods default to calling through to the wrapped request object */
		super(request);

		// Check if we have a File Upload request
		this.hasUploadRequest = ServletFileUpload.isMultipartContent(request);

		// If we have a File Upload request
		this.parseRequest();

	}

	//~ Methods //////////////////////////////////////////////////////////////////
	//****************************************************************************
	@SuppressWarnings("unchecked")
	private void parseRequest() throws FileUploadException {

		// Ignore this step if we haven't a file upload request
		if ( !this.hasUploadRequest ) return;

		/** 1) Create a factory for disk-based file items
	     *  2) Set Repository to Application's temporary directory  */
		DiskFileItemFactory factory = new DiskFileItemFactory();
		factory.setRepository( Application.paths.temporary.getFile() );

		// Process the list of uploaded files
		ServletFileUpload upload = new ServletFileUpload(factory); // Create a new file upload handler
		List<FileItem>    items  = upload.parseRequest(this);      // Parse the request

		// Adapt as WebParmameter both UploadFields and FormFields
		for (FileItem item : items) {
			if (item.isFormField()) {
				this.params.put(item.getFieldName(),new WebParameterForm(item)); // For general fields
			}
			else {
				this.params.put(item.getFieldName(),new WebParameterFile(item)); // For upload fields
				this.uploadCount++;
			}
		}

	}
	//****************************************************************************
	public WebParameter getOctetStream() throws ServletException {

		String contentType = this.getContentType();
		if (contentType == null || !contentType.equals("application/octet-stream")) {
			throw new ServletException(
					"Invalid content type '" + this.getContentType() +
					"'; the expected one was 'application/octet-stream'"
			);
		}
		return new WebParameterOctetStream(this);

	}
	//****************************************************************************
	public WebParameter getWebParameter(String name) {

		// If we have a file upload request,
		if ( this.hasUploadRequest ) {
			WebParameter param = this.params.get(name);
			return (param!=null) ? param : new WebParameterForm(name,this);
		}
		// If we have a general request with no uploads,
		else {
			return new WebParameterForm(name,this);
		}

	}
	//****************************************************************************
	public WebParameter getWebParameter(String name,long maxLength) {

		// Retrieve the parameter
		WebParameter param = this.getWebParameter(name);

		// Check value's length
		if (param.getLength() > maxLength) throw new ParameterException (
			  ( param.isUpload()
			  ? "The file size of the field '"
			  : "The content size of the field '")
			  + name + "' cannot be greater than " + maxLength
			  , param
		);
		return param;

	}
	//****************************************************************************
	public WebParameter getWebParameter(String name,long minLength,long maxLength) {

		// Retrieve the parameter
		WebParameter param = this.getWebParameter(name);

		// Check value's length
		if (param.getLength() < minLength || param.getLength() > maxLength)
		throw new ParameterException (
			  ( param.isUpload()
			  ? "The file size of the field '"
			  : "The content size of the field '")
			  + name + "' cannot be greater than " + maxLength
			  , param
		);
		return param;

	}
	//****************************************************************************
	public WebParameter[] getAllFileParameters() {

		WebParameter[] uploads = new WebParameter[this.uploadCount];
		int i = 0;
		for (WebParameter p : this.params.values()) {
			if (p.isUpload()) uploads[i++] = p;
		}
		return uploads;

	}
	//****************************************************************************

}
